import { type AnyFieldApi, type AnyFormState, useForm } from "@tanstack/vue-form";
import { defineComponent, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { z } from "zod";
import Button from "@/components/Button";
import Input from "@/components/Input";
import Panel from "@/components/Panel";
import useAuthStore from "@/store/auth";

function FieldInfo(p: { state: AnyFieldApi["state"] }) {
  return (
    <>
      {p.state.meta.isTouched && p.state.meta.errors.length ? <em>{p.state.meta.errors[0].message}</em> : null}
      {p.state.meta.isValidating ? "Validating..." : null}
    </>
  );
}

export default defineComponent({
  setup() {
    const auth = useAuthStore();
    const router = useRouter();

    const form = useForm({
      defaultValues: {
        username: "",
        password: "",
      },
      validators: {
        onChange: z.object({
          username: z.string().min(3, "用户名至少应包含3个字符。"),
          password: z.string().min(6, "密码至少应包含6个字符。"),
        }),
      },
      onSubmit: async ({ value }) => {
        const result = await auth.login(value.username, value.password);
        if (result.ok) {
          router.push({ path: "/", replace: true });
        } else {
          alert(result.message);
        }
      },
    });

    // FIXME: 虽然没有类型推断，但是我特么只能做到这种程度了。受不了的话，就用 .vue 单文件组件得了。
    type FieldSlot = { field: AnyFieldApi; state: AnyFieldApi["state"] };

    onMounted(() => {
      if (auth.auth.status === "ok") {
        router.push({ path: "/", replace: true });
      }
    });

    watch(
      () => auth.auth.status,
      (status) => {
        if (status === "ok") {
          router.push({ path: "/", replace: true });
        }
      },
    );

    return () => (
      <Panel class="w-80 mt-12 mx-auto">
        <form
          class="flex flex-col gap-4"
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            form.handleSubmit();
          }}
        >
          <h1>登录</h1>
          <form.Field name="username">
            {{
              default: ({ field, state }: FieldSlot) => (
                <>
                  <label for="username">用户名：</label>
                  <Input
                    name={field.name}
                    value={field.state.value}
                    onBlur={field.handleBlur}
                    onInput={(e) => field.handleChange((e.target as HTMLInputElement).value)}
                  />
                  <FieldInfo state={state} />
                </>
              ),
            }}
          </form.Field>
          <form.Field name="password">
            {{
              default: ({ field, state }: FieldSlot) => (
                <>
                  <label for="password">密码：</label>
                  <Input
                    name={field.name}
                    value={field.state.value}
                    type="password"
                    onBlur={field.handleBlur}
                    onInput={(e) => field.handleChange((e.target as HTMLInputElement).value)}
                  />
                  <FieldInfo state={state} />
                </>
              ),
            }}
          </form.Field>
          <form.Subscribe>
            {{
              default: ({ canSubmit, isSubmitting }: AnyFormState) => (
                <Button type="submit" disabled={!canSubmit}>
                  {isSubmitting ? "..." : "登录"}
                </Button>
              ),
            }}
          </form.Subscribe>
        </form>
      </Panel>
    );
  },
});
